<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="购买用户" prop="buyerName">
        <el-input v-model="queryParams.buyerName" placeholder="请输入购买用户" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="下单时间" prop="orderTimeRange" style="width: 360px">
        <el-date-picker v-model="orderTimeRange" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 180px">
          <el-option v-for="o in orderStatusOptions" :key="o.value" :label="o.label" :value="o.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付类型" prop="payType">
        <el-select v-model="queryParams.payType" placeholder="请选择支付类型" clearable style="width: 180px">
          <el-option v-for="p in payTypeOptions" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain :icon="Delete" :disabled="!selectedRows.length" @click="handleBatchDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain :icon="Download" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-col>
      <div style="margin-left: 16px; align-self: center; color: #000;">
        <b>合计消费金额：{{ totalAmount }} 元</b>
      </div>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" @filter-change="handleFilterChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" type="index" width="70" align="center" :index="indexMethod" />
      <el-table-column label="购买用户" align="center">
        <template #default="scope">{{ scope.row.buyerName || scope.row.userName }}</template>
      </el-table-column>
      <el-table-column label="商品名称" align="center">
        <template #default="scope">{{ scope.row.productName || scope.row.goodsName || scope.row.itemName }}</template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="下单时间" align="center" width="170">
        <template #default="scope">{{ parseTime(scope.row.createTime || scope.row.orderTime) }}</template>
      </el-table-column>
      <el-table-column label="微信支付单号" align="center" prop="outTradeNo" />
      <el-table-column label="订单类型" align="center">
        <template #default="scope">{{ scope.row.orderTypeName || '商品订单' }}</template>
      </el-table-column>
      <el-table-column label="订单金额" align="center">
        <template #default="scope">{{ fmtAmount(scope.row.orderAmount) }} 元</template>
      </el-table-column>
      <el-table-column label="运费" align="center">
        <template #default="scope">{{ fmtAmount(scope.row.freightAmount) }} 元</template>
      </el-table-column>
      <el-table-column label="总金额" align="center">
        <template #default="scope">{{ fmtAmount(scope.row.sumAmount) }} 元</template>
      </el-table-column>
      <el-table-column label="支付类型" align="center">
        <template #default="scope">{{ labelOf(payTypeOptions, scope.row.payType) || scope.row.payTypeName || scope.row.payType }}</template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" width="170">
        <template #default="scope">{{ parseTime(scope.row.payTime) }}</template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" column-key="orderStatus" :filters="statusFilters" :filter-multiple="false">
        <template #default="scope">
          <el-tag :type="statusTypeOf(scope.row.orderStatus ?? scope.row.status)">
            {{ labelOf(orderStatusOptions, scope.row.orderStatus ?? scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流单号" align="center" prop="logisticsCode" />
      <el-table-column label="物流类型" align="center" prop="logisticsType" />
      <el-table-column label="收货人姓名" align="center" prop="takeUser" />
      <el-table-column label="收货人手机号" align="center" prop="takePhone" />
      <el-table-column label="收货人地址" align="center" prop="takeAddress" min-width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="viewDetail(scope.row)">详情</el-button>
          <el-button type="text" style="color: var(--el-color-danger)" @click="handleRowDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="GoodsOrderIndex">
import { ref, reactive, toRefs, computed } from 'vue'
import { Search, Refresh, Download, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
import { listGoodsOrder, delGoodsOrder } from '@/api/system/goodsorder'
import request, { download } from '@/utils/request'

const queryFormRef = ref()
const state = reactive({
  loading: true,
  exportLoading: false,
  showSearch: true,
  total: 0,
  list: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    buyerName: undefined,
    orderCode: undefined,
    orderStatus: undefined,
    payType: undefined,
    orderBeginTime: undefined,
    orderEndTime: undefined,
  }
})

const { loading, exportLoading, showSearch, total, list, queryParams } = toRefs(state)
const orderTimeRange = ref([])
const orderStatusOptions = ref([])
const payTypeOptions = ref([])
const statusFilters = computed(() => (orderStatusOptions.value || []).map(o => ({ text: o.label, value: o.value })))
const selectedRows = ref([])

const totalAmount = computed(() => {
  return (list.value || []).reduce((s, r) => s + (Number(r.sumAmount) || 0), 0)
})

function getList() {
  loading.value = true
  const params = { ...queryParams.value }
  if (params.orderStatus != null && params.status == null) params.status = params.orderStatus
  listGoodsOrder(params).then(res => {
    list.value = res.rows || []
    total.value = res.total || 0
  }).finally(() => { loading.value = false })
}

function handleQuery() {
  queryParams.value.pageNum = 1
  if (Array.isArray(orderTimeRange.value) && orderTimeRange.value.length === 2) {
    queryParams.value.orderBeginTime = orderTimeRange.value[0]
    queryParams.value.orderEndTime = orderTimeRange.value[1]
  } else {
    queryParams.value.orderBeginTime = undefined
    queryParams.value.orderEndTime = undefined
  }
  getList()
}

function resetQuery() {
  queryFormRef.value?.resetFields()
  orderTimeRange.value = []
  handleQuery()
}

function handleSelectionChange(rows) {
  selectedRows.value = rows || []
}

function indexMethod(index) {
  const p = queryParams.value || {}
  const pageNum = Number(p.pageNum || 1)
  const pageSize = Number(p.pageSize || 10)
  return (pageNum - 1) * pageSize + index + 1
}

function fmtAmount(v) { return (Number(v) || 0).toFixed(2) }

function labelOf(options, value) {
  const arr = Array.isArray(options) ? options : (options?.value ?? [])
  const it = (arr || []).find(o => String(o.value) === String(value))
  return it ? it.label : ''
}

function statusTypeOf(value) {
  const it = (orderStatusOptions.value || []).find(o => String(o.value) === String(value))
  const cls = it?.class || it?.listClass || 'default'
  // map backend listClass to Element Plus tag type
  switch (cls) {
    case 'success':
    case 'green':
      return 'success'
    case 'info':
    case 'blue':
      return 'info'
    case 'warning':
    case 'orange':
      return 'warning'
    case 'danger':
    case 'red':
    case 'error':
      return 'danger'
    default:
      return undefined
  }
}

function viewDetail(row) {
  ElMessage.info('查看订单 ' + (row.orderCode || row.id))
}

function loadFilters() {
  return Promise.all([
    // 订单状态字典
    request({ url: '/system/dict/data/type/sys_order_status', method: 'get' }).then(res => {
      const arr = res?.data || []
      orderStatusOptions.value = arr.map(d => ({ label: d.dictLabel, value: String(d.dictValue), class: d.listClass }))
    }).catch(() => {}),
    // 支付类型字典
    request({ url: '/system/dict/data/type/order_info_pay_type', method: 'get' }).then(res => {
      const arr = res?.data || []
      payTypeOptions.value = arr.map(d => ({ label: d.dictLabel, value: String(d.dictValue) }))
    }).catch(() => {})
  ])
}

function handleExport() {
  const params = { ...queryParams.value }
  if (params.orderStatus != null && params.status == null) params.status = params.orderStatus
  ElMessageBox.confirm('是否确认导出筛选的商品订单数据?', '提示', { type: 'warning' }).then(() => {
    exportLoading.value = true
    return request({ url: '/business/goodsorder/export', method: 'get', params })
  }).then(res => {
    download(res.msg)
  }).finally(() => { exportLoading.value = false })
}

function handleFilterChange(filters) {
  if (filters && Object.prototype.hasOwnProperty.call(filters, 'orderStatus')) {
    const v = (filters.orderStatus || [])[0]
    queryParams.value.orderStatus = v
    handleQuery()
  }
}

function handleRowDelete(row) {
  const id = row?.id
  if (!id) {
    ElMessage.warning('缺少订单ID，无法删除')
    return
  }
  ElMessageBox.confirm('确认删除该订单吗？', '提示', { type: 'warning' }).then(() => {
    loading.value = true
    return delGoodsOrder(id)
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  }).finally(() => { loading.value = false })
}

function handleBatchDelete() {
  const ids = (selectedRows.value || []).map(r => r.id).filter(Boolean)
  if (!ids.length) {
    ElMessage.warning('请先选择要删除的订单')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条订单吗？`, '提示', { type: 'warning' }).then(() => {
    loading.value = true
    return Promise.all(ids.map(id => delGoodsOrder(id)))
  }).then(() => {
    ElMessage.success('删除成功')
    getList()
  }).finally(() => { loading.value = false })
}

loadFilters().then(() => getList())
</script>
